<?php
include_once "IDbDriver.php";
class PdoDriver extends Base implements IDbDriver
{
    private $_db = null;
    private $_pstmt = null;

    public function __construct()
    {
        $this->connect();
    }

    public function connect()
    {
        try {
            Logger::debug($this->_buildDSN());
            $this->_db = new PDO(
                $this->_buildDSN(),
                C('db=>user'),
                C('db=>pwd'),
                array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES "UTF8";'));
            if (null !== $this->_db) {
                Logger::log('[Notice] connect success!');
            } else {
                Logger::log('[Error] connect failed');
            }
        } catch (PDOException $e) {
            Logger::log($e);
        }
    }

    public function close()
    {
        if (null !== $this->_db) {
            unset($this->_db);
        }
    }

    /**
     * 生成一个pdo的dsn
     * @return mixed
     */
    private function _buildDSN(){
        //func_get_args — Returns an array comprising a function's argument list
        //$args = func_get_args();
        //call_user_func_array — Call a callback with an array of parameters
        return call_user_func_array('sprintf', array('mysql:host=%s;port=%s;dbname=%s',
            C('db=>host') ? C('db=>host') : 'localhost',
            C('db=>port') ? C('db=>port') : '3306',
            C('db=>dbname') ));
    }

    public function prepare($sql)
    {
        if (null !== $this->_pstmt) {
            $this->_pstmt = null;
        }
        Logger::log("[Info] sql  : " . $sql);
        $this->_pstmt = $this->_db->prepare($sql);
    }

    public function execute()
    {
        if (null === $this->_pstmt) {
            Logger::log('[Error]not prepared statement');
        } else {
            if (false === $this->_pstmt->execute()) {
                Logger::log('[Error] sql error,error info is : ' . $this->_ptstmt->errorInfo());
            } else {
                Logger::log('[Notice] execute success');
            }
        }
    }

    public function getAllByAssocArray()
    {
        return $this->_pstmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public function beginTrans()
    {
        $this->_db->beginTransaction();
    }

    public function commit()
    {
        $this->_db->commit();
    }

    public function rollback()
    {
        $this->_db->rollback();
    }

    /**
     * Version number query string
     *
     * @access	public
     * @return	string
     */
    function _version()
    {
        return $this->_db->getAttribute(PDO::ATTR_CLIENT_VERSION);
    }
}